import Taro from '@tarojs/taro';
import { View, Text, Image,Camera } from '@tarojs/components';
import { AtTextarea, AtModal, AtModalHeader, AtModalContent, AtButton } from 'taro-ui'
import http from '@/utils/http';
import utils from '@/utils/util';

import './index.scss';
import Sunrvey from '@/components/survey/index';
import { get as getGlobalData } from '@/global'

let app = Taro.getApp();
export default class inspectionSubmit extends Taro.Component {
    constructor(props) {
        super(props);
        const now = new Date();
        this.timerID = null;
        this.timer = null;
        this.state = {
            isinit: false,
            Medicine: {},
            isOpened: false,
            picturesArr: [],
            maskContent: '',
            status: {
                record: 'auto',
                camera: 'front'
            },
            MedicalkitId: this.$router.params.MedicalkitId,
            nowtime: `${now.getHours() < 10 ? `0${now.getHours()}` : now.getHours()}:${now.getMinutes() < 10 ? `0${now.getMinutes()}` : now.getMinutes()}`
        }
    }
    componentWillMount() {
        this.getMedicalkitById();
    }
    componentWillUnmount() {
        clearInterval(this.timerID);
        clearInterval(this.timer)
        this.timer = null;
        this.timerID = null;
    }
    config = {
        navigationBarTitleText: '巡检签到'
    }
    componentDidShow() {
        this.timerID = setInterval(
            () => this.tick(),
            1000
        );
    }
    getMedicalkitById() {
        const { MedicalkitId } = this.state;
        http.get('getMedicalkitById', {
            MedicalkitId
        }).then((d) => {
            const { wardid, wardname } = this.$router.params
            this.setState({
                Medicine: {
                    ...d.datas,
                    wardid,
                    wardname
                }
            })
        }).catch((e) => {
            console.log(e);
        })
    }
    tick() {
        const now = new Date();
        this.setState({
            nowtime: `${now.getHours() < 10 ? `0${now.getHours()}` : now.getHours()}:${now.getMinutes() < 10 ? `0${now.getMinutes()}` : now.getMinutes()}`
        });
    }
    uploadImg() {
        let { picturesArr } = this.state;
        utils.uploadImg().then((res) => {
            picturesArr.push(res);
            this.setState({
                picturesArr
            })
        })
    }
    handleChange(e) {
        this.setState({
            maskContent: e.detail.value
        })
    }
    submitInfo() {
        this.setState({
            isOpened: true
        },()=>{
            if (this.state.isinit) {
                this.initCamera();
            }
        })
    }
    checkSet() {
        let userInfo = getGlobalData('userInfo') || utils.getUserInfo();
        let { maskContent, Medicine, picturesArr } = this.state;
        http.post('checkSet', {
            loginid: userInfo.loginid,
            ward: Medicine.wardname,
            mark: maskContent,
            medicalkitid: Medicine.id,
            file: picturesArr.join('|'),
            drugs: Medicine.drugs,
            department: Medicine.departmentname
        }, false, true, true).then((d) => {
            Taro.reLaunch({
                url: '/pages/index/index',
                success: (res) => {
                    setTimeout(() => {
                        Taro.navigateTo({
                            url: '/pages/signRecord/index'
                        })
                    }, 500);
                }
            })
        }).catch(() => { })
    }
    initCamera() {
        if (this.state.isOpened === false) {
            return;
        }
        clearInterval(this.timer);
        this.timer = null;
        this.setState({
            isinit: true
        },()=>{
            setTimeout(() => {
                this.takePhoto();
                this.timer = setInterval(() => {
                    this.setState({
                        isOpened: false
                    }, () => {
                        clearInterval(this.timer);
                        this.timer = null;
                        utils.showtoast('检测人脸超时，请稍后重试');
                    })
                }, 20000)
            }, 500);
        })
    }
    errorCamera() {
        clearInterval(this.timer);
        this.timer = null;
        this.setState({
            isOpened: false
        },()=>{
            Taro.showModal({
                title: '张中医急救',
                content: '为了您更好的使用,请在设置里打开摄像头的权限',
                confirmText: '去打开',
                cancelText: '取消',
                success: (e) => {
                    if (e.confirm) {
                        Taro.openSetting({
                            success: (res) => {
                                if (res.authSetting['scope.camera']) {
                                    this.setState({
                                        isOpened: true
                                    }, () => {
                                        this.initCamera();
                                    })
                                } else {
                                    // utils.showtoast('请在设置里打开摄像头的权限');
                                }
                            },
                            fail(error) {
                                console.log(error);
                            }
                        })
                    } else if (e.cancel) {

                    }
                }
            })
        })
    }
    takePhoto() {
        let { isOpened } = this.state;
        if (this.state.isOpened === false) {
            return;
        }
        let userInfo = getGlobalData('userInfo') || utils.getUserInfo();
        this.ctx = Taro.createCameraContext();
        this.ctx.takePhoto({
            quality: "low",
            success: (photo)=> {
                Taro.getFileSystemManager().readFile({
                    filePath: photo.tempImagePath, //选择图片返回的相对路径
                    encoding: 'base64', //编码格式
                    success: (res)=> {
                        http.post('faceMatch',{
                            loginid: userInfo.loginid,
                            face: res.data
                        }, false,true,false).then((d)=>{
                            if (d.datas.result && d.datas.result.score >= 80) {
                                this.checkSet();
                                clearInterval(this.timer)
                                this.timer = null;
                                utils.showtoast('人脸识别成功')
                                this.setState({
                                    isOpened: false
                                })
                            }else {
                                setTimeout(() => {
                                    this.takePhoto();
                                })
                                if (d.datas.error_msg == 'pic not has face') {
                                    isOpened && utils.showtoast('未检测到人脸，请将手机正对人脸') 
                                }else {
                                    isOpened && utils.showtoast('检测到人脸，但比对失败') 
                                }
                            }
                        }).catch((e)=>{
                            console.log(e);
                            setTimeout(()=>{
                                isOpened &&  utils.showtoast('人脸识别失败,请检查网络或稍后重试')
                            },100)
                            this.setState({
                                isOpened: false
                            })
                        })
                    }
                })
            }
        })
    }
    previewImage(picturesArr, item) {
        app.previewImage(picturesArr, item);
    }
    render() {
        const { nowtime, picturesArr, Medicine, maskContent, isOpened, status } = this.state;
        return (
            <View className='inspection-submit box_s pt-2-5 pl-2-5 pr-2-5'>
                <View className='bdr_10 ov_h fle'>
                    <View className='inspection-submit-center box_s ft26'>
                        <View className='pl-3-5  pt-3 pb-3  pr-3-5 box_s line-b flex flex-r  bg_fff'>
                            <View className='flex flex-r flex-item-v-center'>
                                <Image src={require('../../assets/imgs/sigin/xjqd_icon_xjsj.png')} className='icon-box'></Image>
                                <Text className='fc_333 pl-2'>巡检时间：{nowtime}</Text>
                            </View>
                        </View>
                        <View className='bg_fff pl-3-5  pt-3 pb-3  pr-3-5 box_s line-b flex flex-r flex-item-between flex-item-v-center'>
                            <View className='flex flex-r flex-item-v-center'>
                                <Image style={{ width: Taro.pxTransform(19) }} src={require('../../assets/imgs/sigin/xjqd_icon_qdsj.png')} className='icon-box'></Image>
                                <Text className='fc_333 pl-2'>签到地点：{Medicine.wardname}</Text>
                            </View>
                        </View>
                    </View>
                </View>
                {/* <camera device-position="back" flash="off" binderror="error" style="width: 100%; height: 300px;"></camera>
                    <button type="primary" bindtap="takePhoto">拍照</button> */}

                <AtModal closeOnClickOverlay={false} isOpened={isOpened}>
                    <AtModalHeader>人脸识别</AtModalHeader>
                    <AtModalContent>
                        <View className='pb-2 pt-2'>
                            {isOpened && <Camera device-position={status.camera} onInitdone={(e) => { this.initCamera(e) }} flash='off' onError={(e) => { this.errorCamera(e)}} style={{ width: '100%', height: Taro.pxTransform(600) }}>
                                {/* <cover-view className='frame' style={{left: Taro.pxTransform(frame.left), top: Taro.pxTransform(frame.top), width: Taro.pxTransform(frame.width), height: Taro.pxTransform(frame.height)}}></cover-view> */}
                            </Camera>}
                        </View>
                        <View className='flex flex-item-center flex-1 pt-2'>
                            <AtButton onClick={() => { this.setState({ isOpened: false }, () => { clearInterval(this.timer), this.timer = null;}) }} type='secondary' size='small'>取消识别</AtButton>
                        </View>
                    </AtModalContent>
                </AtModal>
                <View className='bdr_10 ov_h fle pl-3-5 pr-3-5 pt-4-5 pb-3-5 bg_fff mt-2-5 pictures'>
                    {!isOpened&&<AtTextarea
                      count={false}
                      value={maskContent}
                      onChange={this.handleChange.bind(this)}
                      maxLength={200}
                      placeholder='请填写签到备注' className='' style={{ color: 'rgba(134, 139, 156, 1)' }}
                    ></AtTextarea>}

                    <View className='pictures-arr flex flex-r mt-1' >
                        {
                            picturesArr.map((item) => {
                                return (
                                    <View className='pictures-arr-item flex bdr_10' key={item}>
                                        <View className='ov-h flex-1 bdr_10' onClick={() => { this.previewImage(picturesArr, item)}}>
                                            <Image src={item} mode='center' className='pictures-box'></Image>
                                        </View>
                                    </View>
                                )
                            })
                        }
                        {
                            picturesArr.length < 3 ?
                                <View className='pictures-arr-item flex flex-item-center flex-c bdr_10' onClick={() => { this.uploadImg() }} >
                                    <Image className='camera' src={require('../../assets/imgs/sigin/xjqd_img_xj.png')}></Image>
                                    <Text className='mt-2 ft24 fc_999'>{picturesArr.length}/3</Text>
                                </View>
                                : null
                        }

                    </View>
                </View>
                <Sunrvey medicalkit={Medicine} ></Sunrvey>
                <View onClick={() => { this.submitInfo() }} className='default-btn rest-btn ft32  mt-9-5' >提交</View>
            </View>
        );
    }
}